define(['jquery','common'], function($,common){
    var upload = {
        //监听上传按钮
        formImage: function(element){
            $(document).on("click", element, function(){
                //表单上传元素
                var target = $(this).data('target');
                //触发点击事件，弹出选择窗口
                $(target).click();
                //监听表单上传事件
                upload.formImageAjax(target);
            });
        },
        //监听预览按钮
        formPreview: function(element){
            $(document).on("click", element, function(){
                var imgSrc = $($(this).data('target')).val();
                if(imgSrc){
                    common.modal('<img src="'+imgSrc+'" class="img-fluid rounded mx-auto d-block" alt="preview">');
                }else{
                    common.toast('<strong class="text-danger">请先上传图片</strong>',1000);
                }
            });
        },
        //AJAX上传事件
        formImageAjax: function(element){
            $(document).on("change", element, function(){
                var uploadPath = $(this).data('path');
                var targetId   = $(this).data('target');
                var formObj    = $(this)[0].files[0];
                var formData   = new FormData();
                //上传参数KEY/VALUE
                formData.append("file",formObj);
                //上传提示
                common.toast('正在上传',500);
                //AJAX上传
                $.ajax({
                    url: uploadPath,
                    type: 'post',
                    cache: false,
                    data: formData,
                    contentType: false,
                    processData: false,
                    error: function(){
                        common.toast('加载失败',2000);
                    },
                    success: function(res,status,xhr){
                        //填充表单
                        if(res.code == 200){
                            $(targetId).val(res.data.cdnUrl);
                        }
                        //信息提示
                        common.toast(res.msg,1000);
                    }
                });
            });
        }
    };
    return upload;
});